<template>
  <div class="auth-product-box">
    <el-container class="container-box">
      <!-- 头部 -->
      <el-header height="auto">
        <h3>{{ name }}</h3>
        <el-form
          :inline="true"
          ref="formData"
          :model="formData"
          class="formData-box"
        >
          <div>
            <el-form-item
              label="审核状态"
              prop="status">
              <el-select
                v-model="formData.status"
                placeholder="请选择">
                <el-option
                  v-for="(item, index) in searchParams"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              label="生产商名称"
              prop="distributorName">
              <el-input
                v-model="formData.distributorName"
                placeholder="请输入" />
            </el-form-item>
            <!-- <el-form-item
              label="生产商名称"
              prop="manufacturerId">
              <el-select
                v-model="formData.manufacturerId"
                filterable
                remote
                placeholder="请输入"
                :remote-method="remoteMethod"
                :loading="filterableLoading"
              >
                <el-option
                  v-for="item in filterableOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button @click.stop="onClear(formData)">
                <i class="iconfont el-icon-refresh-right"/>
                重置</el-button>
              <el-button
                type="primary"
                @click.stop="onSubmit"
                :class="{'isAddWidth':submitLoading}"
                :loading="submitLoading"
              >
                <i
                  class="iconfont el-icon-search"
                  :class="{'isdisplay':submitLoading}" />
                {{ submitLoading?'':'查询' }}</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-header>
      <!-- 内容 -->
      <el-editable
        class="editable-box"
        :data="tableData"
        v-loading="tableLoading"
        height="200px"
        :columns="productColumns"
      >
        <template
          slot="default-num"
          slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
        <template
          slot="default-rge"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="lookregisterCard(scope)"
            type="text"
          >查看</el-button
          >
        </template>
        <template
          slot="default-auth"
          slot-scope="scope">
          <el-button
            size="small"
            :disabled="true"
            @click.stop="addEnterprise(scope)"
            type="text"
          >查看</el-button
          >
        </template>
      </el-editable>
      <el-pagination
        align="right"
        style="margin-top:20px;"
        @size-change="handleSizeHistory"
        @current-change="handleCurrentHistory"
        :current-page="pageData.page1"
        :page-size="pageData.size1"
        :page-sizes="PAGE_NUMBER1"
        :layout="PAGINATION_LAYOUT1"
        :total="pageData.total1"
      />
      <!-- 添加产品 -->
      <el-dialog
        class="areaTab"
        :title="addText"
        :visible.sync="isShowAddProduct"
        width="1200px"
        @close='closedialog'
      >
        <el-form
          :inline="true"
          :label-width="labelWidth"
          ref="addForm"
          :model="addForm"
          class="addForm-box"
        >
          <div>
            <el-form-item
              label="产品名称"
              prop="chName">
              <el-input
                v-model="addForm.chName"
                placeholder="请输入" />
            </el-form-item>
            <el-form-item
              label="院内编码"
              prop="hosCode">
              <el-input
                v-model="addForm.hosCode"
                placeholder="请输入" />
            </el-form-item>
            <el-form-item
              label="产品编码"
              prop="code">
              <el-input
                v-model="addForm.code"
                placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button
                size="mini"
                @click.stop="onAddClear(addForm)"
              >
                <i class="iconfont el-icon-refresh-right"/>
                重置</el-button
                >
              <el-button
                type="primary"
                size="mini"
                @click.stop="onAddSubmit"
                :class="{'isAddWidth':submitLoadingAdd}"
                :loading="submitLoadingAdd"
              >
                <i
                  class="iconfont el-icon-search"
                  :class="{'isdisplay':submitLoadingAdd}" />
                {{ submitLoadingAdd?'':'查询' }}</el-button
                >
              <el-button
                type="primary"
                size="mini"
                :disabled="checkboxArr.length === 0"
                @click.stop="onSubmitAuth"
              >
                <i class="el-icon-finished"/>
                提交审核</el-button
                >
            </el-form-item>
          </div>
        </el-form>
        <el-editable
          class
          :data="addData"
          v-loading="tableLoadingAdd"
          height="300px"
          :columns="addProductColumns"
          @selection-change="handleSelectionChange"
        >
          <template
            slot="default-price"
            slot-scope="scope">
            <span>{{ Number(scope.row.price).toFixed(2) }}</span>
          </template>
        </el-editable>

        <el-pagination
          align="right"
          style="margin-top:20px;"
          @size-change="handleSizeAdd"
          @current-change="handleCurrentAdd"
          :current-page="pageData.page2"
          :page-size="pageData.size2"
          :page-sizes="PAGE_NUMBER2"
          :layout="PAGINATION_LAYOUT2"
          :total="pageData.total2"
        />
      </el-dialog>
      <!-- 注册证查看详情 -->
      <el-dialog
        class="area"
        title="注册证"
        :visible.sync="isShowAudited"
        width="1000px"
      >
        <el-form
          :inline="false"
          class="details-form">
          <el-form-item
            v-for="(item, i) in detailscolumns"
            :key="i"
            class="A-line"
            :class="{'A-line-color': i % 2 === 0}"
          >
            <span class="leftspan">
              {{ item.title + '' }}
            </span>
            <span
              v-if="
                item.key !== 'dr' &&
                  item.key !== 'type' &&
                  item.key !== 'associationCertificates'
              "
            >{{
              certificateForm.settlemObjValue
                ? certificateForm.settlemObjValue[item.key]
                : ''
            }}</span
            >
            <span v-if="item.key === 'dr'">
              {{
                certificateForm.settlemObjValue.dr
                  ? drMap[certificateForm.settlemObjValue.dr]
                  : ''
              }}</span
              >
            <span v-if="item.key === 'type'">
              {{
                certificateForm.settlemObjValue.type
                  ? typeMap[certificateForm.settlemObjValue.type]
                  : ''
              }}</span
              >
            <span v-if="item.key === 'associationCertificates'">
              {{ associationCertificatesValue }}
            </span>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-container>
  </div>
</template>
<script>
import paginationMixin from '@mixins/paginationMixin'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import ElEditable from '@components/el-editable/index.vue'
import {
  productColumns,
  attrColumns1,
  searchParams,
  addProductColumns,
  detailscolumns,
  typeMap,
  drMap
} from './const.js'
import {
  findProdItemByHos,
  submitApply,
  getApplyProdByConstrict,
  getCertificate,
  hospitalDownList
} from '@const/beforeSettleApi.js'
import { hasIn } from 'lodash'
export default {
  mixins: [paginationMixin],
  components: { ElEditable },
  data () {
    return {
      submitLoading: false,
      submitLoadingAdd: false,
      associationCertificatesValue: '', // 关联的注册证
      filterableLoading: false, // 生产厂商模糊搜索loading
      filterableOptions: [], // 生产厂商模糊搜索列表
      // 查看注册证审核详情表头
      detailscolumns,
      typeMap,
      drMap,
      pageData: {
        page1: 1,
        page2: 1,
        size1: 20,
        size2: 20,
        total1: 0,
        total2: 0
      },
      certificateForm: {
        settlemObjValue: {}
      },
      name: '',
      isShowAddProduct: false,
      addText: '添加产品（已选中 0 个)',
      //   添加产品
      addData: [],
      addProductColumns,
      addForm: {
        chName: '',
        hosCode: '',
        code: ''
      },
      checkboxArr: [],

      labelWidth: '82px',
      tableLoading: false,
      tableLoadingAdd: false,
      //   列表搜索
      formData: {
        status: null,
        distributorName: ''
      },
      searchParams, // 状态
      //   列表产品
      tableData: [],
      productColumns,
      isShowAudited: false, // 控制产品详情弹框是否显示
      PAGE_NUMBER1: PAGE_NUMBER, // 分页类型
      PAGINATION_LAYOUT1: PAGINATION_LAYOUT,
      PAGE_NUMBER2: PAGE_NUMBER, // 分页类型
      PAGINATION_LAYOUT2: PAGINATION_LAYOUT

      // PAGINATION_LAYOUT // 分页功能 this.page.total = hasIn(data, ['payload', 'totalElements']) ? data.payload.totalElements : 0
    }
  },
  created () {
    this.initNavButtons()
    this.name = this.$route.query.name
    if (this.$route.query.status) {
      this.formData.status = Number(this.$route.query.status)
    }
    this.getList()
    this.remoteMethod('')
  },
  methods: {
    // 关闭弹框重置一切数据
    closedialog () {
      this.$refs.addForm.resetFields()
    },
    // 处理注册证详情弹框中关联的注册证字段显示方式
    associationCertificatesForeach (ary) {
      let str = ``
      ary.forEach(item => {
        for (let key in item) {
          if (item[key]) {
            str += item[key] + ' , '
          }
        }
      })
      return str
    },
    list (id) {
      this.certificateForm.tableLoading = true
      this.$axios({
        method: 'get',
        url: getCertificate,
        params: {
          id
        }
      })
        .then(res => {
          let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
          this.certificateForm.settlemObjValue = obj
          let associationCertificates = obj.associationCertificates
          this.associationCertificatesValue = this.associationCertificatesForeach(
            associationCertificates
          )
        })
        .finally(res => {
          this.certificateForm.tableLoading = false
        })
    },
    // 模糊搜索生产厂商下拉
    remoteMethod (val) {
      this.filterableLoading = true
      this.$axios
        .$get(hospitalDownList, {
          params: {
            name: val,
            type: 'factory'
          }
        })
        .then(res => {
          this.filterableLoading = false
          this.filterableOptions = hasIn(res, 'payload') ? res.payload : []
        })
        .finally(res => {})
    },
    // 添加产品-列表
    getAddProductList () {
      this.tableLoadingAdd = true
      this.submitLoadingAdd = true
      const data = {
        ...this.addForm,
        constrictId: this.$route.query.id,
        // hospitalId: this.$route.query.enterpriseId,
        // authId: this.$route.query.id,
        page: this.pageData.page2,
        pageSize: this.pageData.size2
      }
      this.$axios
        .post(findProdItemByHos, data)
        .then(res => {
          const { data } = res
          if (!Number(data.code)) {
            this.addData = hasIn(data, ['payload', 'content'])
              ? data.payload.content
              : []
            this.pageData.total2 = hasIn(data, ['payload', 'totalElements'])
              ? data.payload.totalElements
              : 0
            // this.pageData.total2 = data.payload.totalElements || 0
            // let arr = this.checkboxArr
            // console.log('arr--', arr)
            // if (arr) {
            //   arr.forEach(row => {
            //     // console.log(row)
            //     // this.$refs.multipleTable.toggleRowSelection(row);
            //   })
            // }
          }
        })
        .finally(() => {
          this.submitLoadingAdd = false
          this.tableLoadingAdd = false
        })
    },
    // 添加产品-搜索
    onAddSubmit () {
      this.pageData.page2 = 1
      this.getAddProductList()
    },
    // 添加产品-重置
    onAddClear () {
      this.$refs['addForm'].resetFields()
    },
    // 添加产品-提交审核
    onSubmitAuth () {
      // this.isShowAddProduct = false
      // let data = this.checkboxArr.map(item => {
      //   return item.id
      // })
      let data = []
      this.checkboxArr.map(item => {
        let obj = {
          distributorProdItemId: item.id,
          distributorProdCode: item.code,
          hosAuthItemId: item.hosProdId,
          hosProdCode: item.hosCode,
          hospitalId: item.hosId,
          hospitalName: item.hosName,
          distributorId: this.$store.state.companyId,
          distributorName: this.$store.state.companyName,
          constrictId: this.$route.query.id,
          expireDate: this.$route.query.validityTo,
          linkMan: this.$route.query.user,
          linkPhone: this.$route.query.phone
        }
        data.push(obj)
      })
      // console.log(data)
      this.$axios.post(submitApply, { applyList: data }).then(res => {
        if (res.data.code === '0') {
          this.$message({
            type: 'success',
            message: '提交成功！'
          })
          this.isShowAddProduct = false
          this.getList()
        }
      })
    },
    // 历史产品-列表
    getList () {
      this.tableLoading = true
      this.submitLoading = true
      const data = {
        // enterpriseId: this.$route.query.enterpriseId || null,
        // authId: this.$route.query.id,
        constrictId: this.$route.query.id,
        distributorId: this.$store.state.companyId,
        page: this.pageData.page1,
        pageSize: this.pageData.size1,
        ...this.formData
      }
      this.$axios
        .post(getApplyProdByConstrict, data)
        .then(res => {
          const { data } = res
          if (!Number(data.code)) {
            this.tableData = hasIn(data, ['payload', 'content'])
              ? data.payload.content
              : []
            this.pageData.total1 = data.payload.totalElements || 0
          }
        })
        .finally(() => {
          this.tableLoading = false
          this.submitLoading = false
        })
    },
    // 列表-查询
    onSubmit () {
      this.pageData.page1 = 1
      this.getList()
    },
    // 列表-重置
    onClear () {
      this.$refs['formData'].resetFields()
      this.formData.status = null
    },
    // 查看注册证
    lookregisterCard (e) {
      if (!e.row.registId) {
        this.$message({
          type: 'warning',
          message: '此产品暂时没有注册证！',
          duration: '800'
        })
      } else {
        this.isShowAudited = true
        this.list(e.row.registId)
        // this.regCard = true
        // this.$axios
        //   .$get(getCertificate, {
        //     params: {
        //       id: e.row.certificateId
        //     }
        //   })
        //   .then(res => {
        //     if (res.payload.licenseUrl) {
        //       this.$pdfViewer({ url: res.payload.licenseUrl, title: '注册证' })
        //     }
        //   })
      }
    },
    // 列表-添加产品按钮
    toAdd () {
      this.isShowAddProduct = true
      this.getAddProductList()
    },
    goBack () {
      this.$router.go(-1)
    },
    // 初始化 导航栏 按钮组
    initNavButtons () {
      let state = Number(this.$route.query.authState)
      let obj = {
        type: 'btn',
        arr: [
          {
            val: '返回',
            handle: this.goBack
          },
          {
            val: '添加',
            disabled: state !== 3,
            type: 'primary',
            handle: this.toAdd
          }
        ]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    // 复选框触发事件
    handleSelectionChange (arr) {
      this.checkboxArr = arr
      // let e = arr
      // this.checkboxArr = this.checkboxArr.concat(e)
      this.addText = '添加产品（已选中 ' + this.checkboxArr.length + ' 个)'
    },
    // 查看注册证
    addEnterprise () {},
    // 分页
    handleSizeHistory (size) {
      this.pageData.size1 = size
      this.getList()
    },
    handleCurrentHistory (curPage) {
      this.pageData.page1 = curPage
      this.getList()
    },
    handleSizeAdd (size) {
      this.pageData.size2 = size
      this.getAddProductList()
    },
    handleCurrentAdd (curPage) {
      this.pageData.page2 = curPage
      this.getAddProductList()
    }
  }
}
</script>
<style lang="less" scoped>
.auth-product-box {
  .container-box {
    height: 100%;
    overflow: auto;

    h3 {
      margin: 10px 0;
    }
  }
  .A-line-color {
    background: rgba(248, 249, 251, 1);
  }

  .A-line {
    margin: 0;
    height: 46px;
    width: 100%;
    .leftspan {
      width: 270px;
      line-height: 46px;
      padding-left: 10px;
      display: inline-block;
    }
  }
}
</style>
